package com.shizhanzhe.zxbapp;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.zxbapp.bean.Divide;
import com.shizhanzhe.zxbapp.bean.LoginResponse;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.ui.LoginActivity;

import com.shizhanzhe.zxbapp.ui.WelcomeGuideActivity;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.AdPreference;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.SharedPreferencesUtils;
import com.shizhanzhe.zxbapp.utils.Util;

import java.io.File;

/**
 * Created by zz9527 on 2018/10/22.
 */
public class SplashActivity extends Activity {


    boolean isRun = true;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mtime--;
            tvdao.setText(mtime + "");
            if (mtime == 0&&isRun) {
                isShareprefence();
                isRun = false;
                finish();
            }
        }
    };
    private ImageView iv_img;
    private int time = 3000;
    private int mtime = 5;
    private TextView tvdao;
    private boolean welcomeFirst=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        iv_img = findViewById(R.id.iv_img);
        View tiaoguo = findViewById(R.id.ll_tiaoguo);
        tvdao = findViewById(R.id.tv_dao);
        imgUrl = AdPreference.getInstance().getStartupAdPage().getRelatedUrl();
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        if ("".equals(imgUrl)) {
            tiaoguo.setVisibility(View.GONE);
            mtime=3;
        } else {
            mtime=5;
            tiaoguo.setVisibility(View.VISIBLE);
            tiaoguo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    isShareprefence();
                    isRun = false;
                    finish();

                }
            });
        }
        if (Build.VERSION.SDK_INT < 23) {
            GO();
        } else {
            checkPermissions();
        }

        iv_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!"".equals(imgUrl)) {
                    Uri uri = Uri.parse(imgUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
            }
        });
    }
    private void GO(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRun) {
                    try {
                        Thread.sleep(1000);
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
        isFirst();
        if (SharedPreferencesUtils.getDevice(this) == 0) {
            try {
                welcomeFirst=true;
                deviceRegister(Util.androidId(this));
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        getDivide();
    }
    private void isShareprefence(){
        if (welcomeFirst){
            startActivity(new Intent(SplashActivity.this, WelcomeGuideActivity.class));
            return;
        }
        if (SharedPreferencesUtils.getDevice(this) != 0) {
            if ((int) SharedPreferencesUtils.getParam(this, "uid", 0) != 0) {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            } else {
                startActivity(new Intent(SplashActivity.this, LoginActivity.class));
            }
        } else {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
        }
    }
    private void deviceRegister(String device) throws PackageManager.NameNotFoundException {

        OkHttpDownloadJsonUtil.downloadJson(SplashActivity.this, Path.deviceRegister + "?device=" + device+"&channel="+ Util.getChannel(this),
                new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
//                            Log.i("_________",json);
                            Gson gson = new Gson();
                            LoginResponse user = gson.fromJson(json, LoginResponse.class);
                            UserBean.uid = user.getData().getUid();
                            UserBean.pid = user.getData().getPid();
                            UserBean.mobile = user.getData().getMobile();
                            UserBean.headimg = user.getData().getAvatar();
                            UserBean.nickname = user.getData().getNickname();
                            UserBean.sex = user.getData().getSex();
                            UserBean.birthday = user.getData().getBirthday();
                            UserBean.job = user.getData().getJob();
                            UserBean.balance = user.getData().getBalance();
                            UserBean.level = user.getData().getLevel();
                            UserBean.gao = user.getData().getGaotype();
                            UserBean.qudao=user.getData().getChannel();
                            SharedPreferencesUtils.setParam(SplashActivity.this, "uid", UserBean.uid);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "mobile", UserBean.mobile);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "headimg", UserBean.headimg);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "nickname", UserBean.nickname);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "sex", UserBean.sex);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "birthday", UserBean.birthday);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "job", UserBean.job);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "balance", UserBean.balance);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "level", UserBean.level);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "gaotype", UserBean.gao);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "qudao", UserBean.qudao);
                            SharedPreferencesUtils.setDevice(SplashActivity.this);
                        } else {
                            Toast.makeText(SplashActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void getDivide() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.DIVIDE(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                    Gson gson = new Gson();
                    Divide.ParameBean parame = gson.fromJson(json, Divide.class).getParame();
                    UserBean.divide = parame.getTask();
                    UserBean.vipdivide = parame.getViptask();
                    UserBean.carddivide = parame.getCardtask();
                    UserBean.vipcarddivide = parame.getCardviptask();
                    UserBean.ip = parame.getIpconfig();
                    UserBean.subnum=parame.getSubnum();
                    UserBean.subprice=parame.getSubprice();
                    SharedPreferencesUtils.setParam(SplashActivity.this, "divide", UserBean.divide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "vipdivide", UserBean.vipdivide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "carddivide", UserBean.carddivide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "vipcarddivide", UserBean.vipcarddivide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "ip", UserBean.ip);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "subnum", UserBean.subnum);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "subprice", UserBean.subprice);
                    }catch (Exception e){}
                } else {
                    Toast.makeText(SplashActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    String imgUrl = "";

    private void isFirst() {
        String AD_PATH = "";
        AD_PATH = Environment.getExternalStorageDirectory() + "/MFAd/" + Util.getImgName(AdPreference.getInstance().getStartupAdPage().getPicUrl());
        File file = new File(AD_PATH);
        Bitmap bm = BitmapFactory.decodeFile(AD_PATH);

        if (file.exists() && bm != null) {
            iv_img.setScaleType(ImageView.ScaleType.FIT_XY);
            iv_img.setImageBitmap(bm);
        } else {
            iv_img.setScaleType(ImageView.ScaleType.FIT_CENTER);
            Util.deleteFile(AD_PATH);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }


    /**
     * 小tips:这里的int数值不能太大，否则不会弹出请求权限提示，测试的时候,改到1000就不会弹出请求了
     */
    private final static int READ_PHONE_STATE_CODE = 101;

    private final static int WRITE_EXTERNAL_STORAGE_CODE = 102;

    /**
     * 有米 Android SDK 所需要向用户申请的权限列表
     */
    private static PermissionModel[] models = new PermissionModel[] {
            new PermissionModel(Manifest.permission.ACCESS_COARSE_LOCATION, "我们需要使用位置", WRITE_EXTERNAL_STORAGE_CODE),
//			new PermissionModel(Manifest.permission.CAMERA, "我们需要使用相机获取头像", WRITE_EXTERNAL_STORAGE_CODE),
            new PermissionModel(Manifest.permission.READ_PHONE_STATE, "我们需要读取手机信息的权限来标识您的身份", READ_PHONE_STATE_CODE),
            new PermissionModel(Manifest.permission.WRITE_EXTERNAL_STORAGE, "我们需要您允许我们读写你的存储卡，以方便我们临时保存一些数据",
                    WRITE_EXTERNAL_STORAGE_CODE),
    };

    private void checkPermissions() {
        try {

            for (PermissionModel model : models) {
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, model.permission)) {
                    ActivityCompat.requestPermissions(this, new String[] { model.permission }, model.requestCode);
                    return;
                }
            }

            // 到这里就表示所有需要的权限已经通过申请，权限已经申请就打开demo
            GO();
        } catch (Throwable e) {
            Log.e("YoumiSdk", "", e);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {

            case READ_PHONE_STATE_CODE:
            case WRITE_EXTERNAL_STORAGE_CODE:
                // 如果用户不允许，我们视情况发起二次请求或者引导用户到应用页面手动打开
                if (PackageManager.PERMISSION_GRANTED != grantResults[0]) {

                    // 二次请求，表现为：以前请求过这个权限，但是用户拒接了
                    // 在二次请求的时候，会有一个“不再提示的”checkbox
                    // 因此这里需要给用户解释一下我们为什么需要这个权限，否则用户可能会永久不在激活这个申请
                    // 方便用户理解我们为什么需要这个权限
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
                        new AlertDialog.Builder(this).setTitle("权限申请").setMessage(findPermissionExplain(permissions[0]))
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        checkPermissions();
                                    }
                                }).show();
                    }
                    // 到这里就表示已经是第3+次请求，而且此时用户已经永久拒绝了，这个时候，我们引导用户到应用权限页面，让用户自己手动打开
                    else {
                        Toast.makeText(this, "部分权限被拒绝获取，将会会影响后续功能的使用，建议重新打开", Toast.LENGTH_LONG).show();
                        openAppPermissionSetting(123456789);
                    }
                    return;
                }

                // 到这里就表示用户允许了本次请求，我们继续检查是否还有待申请的权限没有申请
                if (isAllRequestedPermissionGranted()) {
                    GO();
                } else {
                    checkPermissions();
                }
                break;
            default:
                break;
        }
    }

    private String findPermissionExplain(String permission) {
        if (models != null) {
            for (PermissionModel model : models) {
                if (model != null && model.permission != null && model.permission.equals(permission)) {
                    return model.explain;
                }
            }
        }
        return null;
    }

    private boolean isAllRequestedPermissionGranted() {
        for (final PermissionModel model : models) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, model.permission)) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case 123456789:
                if (isAllRequestedPermissionGranted()) {
                    GO();
                } else {
                    Toast.makeText(this, "部分权限被拒绝获取，退出", Toast.LENGTH_LONG).show();
                    this.finish();
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private boolean openAppPermissionSetting(int requestCode) {
        try {
            Intent intent =
                    new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + this.getPackageName()));
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            // Android L 之后Activity的启动模式发生了一些变化
            // 如果用了下面的 Intent.FLAG_ACTIVITY_NEW_TASK ，并且是 startActivityForResult
            // 那么会在打开新的activity的时候就会立即回调 onActivityResult
            // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, requestCode);
            return true;
        } catch (Throwable e) {
            Log.e("Permission", "", e);
        }
        return false;
    }

    public static class PermissionModel {

        /**
         * 请求的权限
         */
        public String permission;

        /**
         * 解析为什么请求这个权限
         */
        public String explain;

        /**
         * 请求代码
         */
        public int requestCode;

        public PermissionModel(String permission, String explain, int requestCode) {
            this.permission = permission;
            this.explain = explain;
            this.requestCode = requestCode;
        }
    }

}
